import { defineComponent, h , toRefs, watch, onMounted, onUnmounted } from 'vue'
import planeImage from '../../resource/assets/plane.png'
import useKeyBoard from  '.././use/useKeyboard' 
import game  from '../Game'


export default defineComponent({
  props: ['x','y'],
  setup(props, ctx) {
    //普通解构会导致响应式丢失
    const {x, y} = toRefs(props)
    let isAttack = false
    let startTime = 0
    const AttackInterval = 5

    let startAttack = () => isAttack = true
    let stopAttack = () => isAttack = false
    const Attacking = () => {
        startTime++
        if (startTime > AttackInterval && isAttack) {
          // 开始攻击
          ctx.emit('attack', {x, y})
          startTime = 0
          console.log('attack emit');
        }
    }

    useKeyBoard({
      Space:{
        keydown: startAttack,
        keyup: stopAttack
      }
    })
  
    onMounted(()=> {
      game.ticker.add(Attacking)
    })  

    onUnmounted(()=>{
      game.ticker.remove(Attacking)
    })

    return {
      x,
      y
    }

  },
  render(ctx) {
    return  h('Container', {x:ctx.x, y:ctx.y} , [ 
      h('Sprite', {texture: planeImage , width: 130, height: 150 })
    ])
  }
})